<?

function bing_extract_image_search_results($bing) {

    $images = array();
	
    $temp = @$bing['SearchResponse']['Image']['Results'];
	
	if (is_array($temp)) {
	
		foreach ($temp as $slice) {
			array_push($images, $slice['MediaUrl']);
		}
	
    	return array_slice($images, 0, 10);
	
	} else {
		return array();
	}
}
 

function bing_image_search($s) {
    $APP_ID = "6607D806CC3E5E2F29E754BE0B1DC1D740E5B653";
    $SEARCH = "http://api.bing.net/json.aspx?AppId=".$APP_ID."&Version=2.0&Market=en-US&Sources=Image&Image.Count=10&Image.Offset=0&Image.Filters=Size:small&Query=".urlencode($s);
 
    $reply = json_decode(file_get_contents($SEARCH), true);

    // make sure at this point that the bing reply has some valid data!

    $reply_ex = bing_extract_image_search_results($reply);

    return $reply_ex;

}

/*
 * Echo the search results out to STDOUT only if the client is requesting the 
 * images.php script.  This is required to distinguish from the case where 
 * the client invokes a script other than images.php but that script includes 
 * images.php  
 */
if (strpos($_SERVER['PHP_SELF'], "/images.php") > 0) {

    $header = array($_GET['search']);
    $images = bing_image_search($_GET['search']);
 
    $merge = array_merge($header, $images);

    echo json_encode($merge);
}

?>